from django import forms
from django.contrib.auth.models import User
from CourseHub.models import UserProfile
from django.core.exceptions import ObjectDoesNotExist
import re

class registration(forms.Form):
    username = forms.CharField(label='Username', max_length= 30)
    email = forms.EmailField(label='Email')
    # university = forms.CharField(label='Username', max_length= 30)
    password = forms.CharField(label='Password', widget=forms.PasswordInput())
    repassword = forms.CharField(label='Confirm', widget=forms.PasswordInput())

    def clean_username(self):
        username = self.cleaned_data['username']
        if not re.search(r'^\w+$', username):
            raise forms.ValidationError ('Format Exception')
        try:
            User.objects.get(username=username)
        except ObjectDoesNotExist:
            return username
        raise forms.ValidationError('Username existed')

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            User.objects.get(email=email)
        except ObjectDoesNotExist:
            return email
        raise forms.ValidationError ('Email existed')
    
    def clean_password2(self):
        if 'password' in self.cleaned_data:
            password = self.cleaned_data['password']
            repassword = self.cleaned_data['repassword']
            if password == repassword:
                return repassword
            raise forms.ValidationError('No match')